<template>
  <div>
    <el-table class="publicTable" :data="newTableData" max-height="45vh" v-loading="loading" style="border: 1px solid #e6ebf5;" border>
      <el-table-column :show-overflow-tooltip="true" prop="fullName" label="文件名">
        <template slot-scope="scope">
          <div style="line-height: 14px;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;">
            <span v-if="ifImg(scope.row.ext)">
              <!-- ***后台提供缩略图 -->
              <el-image :src="require('@/assets/icons/'+'Application/picture.png')" slot="prefix" :icon-class="scope.row.icon" style="width: 16px;" />
            </span>
            <!-- ***文档类型需要确认种类 -->
            <span v-else-if="(scope.row.ext=='doc'||scope.row.ext=='docx'||scope.row.ext=='xlsx'||scope.row.ext=='xls'||scope.row.ext=='pdf')&&(scope.row.icons[0]!=null)">
              <el-image :src="require('@/assets/icons/'+scope.row.icons[0].icon)" slot="prefix" :icon-class="scope.row.icon" style="width: 16px;" />
            </span>
            <span v-else>
              <el-image :src="require('@/assets/icons/'+'Application/file.png')" slot="prefix" :icon-class="scope.row.icon" style="width: 16px;" />
            </span>
            {{ scope.row.fullName }}
          </div>
        </template>
      </el-table-column>
      <el-table-column :show-overflow-tooltip="true" prop="size" label="文件大小" min-width="50">
        <template slot-scope="scope">
          <span>{{getLateSize(scope.row.size)}}</span>
        </template>
      </el-table-column>
      <el-table-column :show-overflow-tooltip="true" prop="ext" label="文件类型" min-width="40"></el-table-column>
      <el-table-column :show-overflow-tooltip="true" prop="createUser" label="上传人" min-width="50"></el-table-column>
      <el-table-column :show-overflow-tooltip="true" prop="createTime" label="上传时间" min-width="100"></el-table-column>
<!--      <el-table-column :show-overflow-tooltip="true" prop="converterStatus" label="转换状态" min-width="40" >
        <template slot-scope="scope">
          <span v-if="scope.row.uploadtypeId.includes('upload_type_vcollab')">{{getState(scope.row.converterStatus)}}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>-->
<!--      <el-table-column :show-overflow-tooltip="true" prop="remarks" label="说明" class="fileRemarks">
      </el-table-column>-->
      <el-table-column  label="操作" min-width="80">
        <template slot-scope="scope">
          <!--  <el-button v-if="scope.row.ext=='png'||scope.row.ext=='jpg'" @click="imgCompareBtn(scope.row)" type="text" size="small">图片对比</el-button>
            <el-button @click="lookOver(scope.row)" type="text" size="small">查看</el-button>
            <el-button @click="downloadFile(scope.row)" type="text" size="small">下载</el-button>
            <el-button v-if="scope.row.uploadtypeId.includes('upload_type_vcollab')" @click="openFile(scope.row)" type="text" size="small">打开</el-button>-->

          <el-image :src="require('@/assets/icons/action/view.png')" slot="prefix" @click="lookOver(scope.row)" style="width: 25px;margin-top:5px;margin-right: 3px" />
          <el-image :src="require('@/assets/icons/action/download.png')" slot="prefix" @click="downloadFile(scope.row)" style="width: 25px;margin-top:5px;margin-right: 3px" />
          <el-image v-if="scope.row.ext=='png'||scope.row.ext=='jpg'" :src="require('@/assets/icons/action/compare.png')" slot="prefix" @click="imgCompareBtn(scope.row)" style="width: 25px;margin-top:5px;margin-right: 3px" />
          <el-image v-for="(item, index) in scope.row.icons" :src="require('@/assets/icons/'+item.icon)" slot="prefix" @click="openFile(scope.row,item.uniqueKey)" style="width: 25px;margin-top:5px;margin-right: 3px" />
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total/queryParams.pageSize>1" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getFiles" />
    <!-- 图片对比弹窗 -->
    <el-dialog :visible.sync="openImgComDialog" :close-on-click-modal="false" width="63%" append-to-body>
      <el-row :gutter="20" style="margin-bottom:10px">
        <!-- 图片对比缩放区 -->
        <el-col :span="20">
          <div>
            <el-row :gutter="5">
              <el-col :span="12" v-for="(item, idx) in imgArr" :key="idx">
                <div ref="imgWrap" @mousewheel.prevent="rollImg(idx)" class="modal-img-wrap">
                  <!-- @mousedown.stop.prevent="moveImg($event,idx)"--图片移动（暂停） -->
                  <img :ref="'img' + idx" :src="item.url" class="modal-img" />
                </div>
              </el-col>
            </el-row>
          </div>
        </el-col>
        <!-- 图片选择区 -->
        <el-col :span="4">
          <div>
            <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="checkAllChange">全选</el-checkbox>
            <div style="margin: 15px 0;"></div>
            <el-checkbox-group v-model="checkedImgs" @change="checkedImgsChange">
              <el-checkbox v-for="(i,idx) in imgOptions " :label="i.id" :key="idx">{{i.name}}</el-checkbox>
            </el-checkbox-group>
          </div>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import {listFile, getAllImages, downloadFile, fileView, openFileView} from "@/api/form/file";

export default {
  name: 'publicTableShow',
  props: {
    // 需要的参数
    col: {
      type: Object,
      required: false,
      default: () => { }
    },
    partId: {
      type: String,
      required: true,
      default: ""
    },
    fieldId: {
      type: String,
      required: true,
      default: ""
    },
    updateDate:{
      type: String,
      required: false,
      default: ""
    }
  },
  data () {
    return {
      // 遮罩层
      loading: true,
      // 表格数据-sta
      imgOptions: [],
      checkedImgs: [],
      checkAll: false,
      isIndeterminate: true,
      openImgComDialog: false,
      imgArr: [],//展示用图
      imgArrAll: [],//接口获取的所有图
      //上传列表-sta
      newTableData: [],
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        partId: "",
        fieldId: "",
      },
      filesUpdated:false
    };
  },
  watch: {
    partId: {
      handler (n, o) {
        this.getFiles();
      }
    },
    updateDate:{
      handler (n1, o1) {
        this.getFiles();
      }
    }
  },
  created () {
    this.getFiles();
  },
  methods: {
    // 获取最后文件大小
    getLateSize (size) {
      var data = "";
      if (size < 0.1 * 1024) { //如果小于0.1KB转化成B
        data = size.toFixed(2) + "B";
      } else if (size < 0.1 * 1024 * 1024) {//如果小于0.1MB转化成KB
        data = (size / 1024).toFixed(2) + "KB";
      } else if (size < 0.1 * 1024 * 1024 * 1024) { //如果小于0.1GB转化成MB
        data = (size / (1024 * 1024)).toFixed(2) + "MB";
      } else { //其他转化成GB
        data = (size / (1024 * 1024 * 1024)).toFixed(2) + "GB";
      }
      return data
    },
    // 转换状态
    getState (state) {
      let s = "";
      if (state == "0") {
        s = "未转换";
      } else if (state == "1") {
        s = "转换成功";
      } else if (state == "-1") {
        s = "转换失败";
      }
      return s;
    },
    // 图片移动--后续-未完待续
    // moveImg (e, index) {
    //   e.preventDefault()
    //   // 获取元素
    //   let imgWrap = this.$refs.imgWrap
    //   let img = this.$refs[`img${index}`][0]
    //   let x = e.pageX - img.offsetLeft
    //   let y = e.pageY - img.offsetTop
    //   // 添加鼠标移动事件
    //   imgWrap.addEventListener('mousemove', move)
    //   function move (e) {
    //     img.style.left = e.pageX - x + 'px'
    //     img.style.top = e.pageY - y + 'px'
    //   }
    //   // 添加鼠标抬起事件，鼠标抬起，将事件移除
    //   img.addEventListener('mouseup', () => {
    //     imgWrap.removeEventListener('mousemove', move)
    //   })
    //   // 鼠标离开父级元素，把事件移除
    //   imgWrap.addEventListener('mouseout', () => {
    //     imgWrap.removeEventListener('mousemove', move)
    //   })
    // },
    //图片对比-sta
    checkAllChange (val) {
      // val-true是全选，false-全取消
      this.checkedImgs = []
      this.imgArr = []
      if (val) {
        this.checkedImgs = this.imgOptions.map(i => {
          return i.id
        });
        this.isIndeterminate = false;
        this.imgArr = this.imgArrAll
      }
    },
    checkedImgsChange (checkedArr) {
      // 用于全选勾选框状态变化-sta
      let checkedCount = checkedArr.length;
      this.checkAll = checkedCount === this.imgOptions.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.imgOptions.length;
      // -end
      // 根据勾选设置展示图片
      this.imgArr = []
      this.imgArr = this.imgArrAll.filter(item => {
        return checkedArr.indexOf(item.id) != -1
      })
    },
    imgCompareBtn () {
      getAllImages({ fieldId: this.fieldId, partId: this.partId }).then(response => {
        let data = response.data
        this.imgArr = data.map(item => {
          item.url = process.env.VUE_APP_BASE_API + '/file/download/resource?resource=' + item.relativePath
          return item
        })
        this.imgArrAll = JSON.parse(JSON.stringify(this.imgArr))
        this.imgOptions = data.map(item => {
          return { id: item.id, name: item.name }
        })
        this.openImgComDialog = true
      })
    },
    rollImg (index) {
      /* 获取当前页面的缩放比 若未设置zoom缩放比，则为默认100%，即1，原图大小 */
      var zoom = parseInt(this.$refs[`img${index}`][0].style.zoom) || 100
      /* event.wheelDelta 获取滚轮滚动值并将滚动值叠加给缩放比zoom wheelDelta统一为±120，其中正数表示为向上滚动，负数表示向下滚动 */
      zoom += event.wheelDelta / 12
      /* 最小范围 和 最大范围 的图片缩放尺度 */
      if (zoom >= 20 && zoom < 1000) {
        this.$refs[`img${index}`][0].style.zoom = zoom + '%'
      }
      return false
    },
    //表格数据-sta
    // 判断是否是图片
    // 下载文件
    downloadFile (file) {
      downloadFile(file.id).then(response => {
      })
    },
    ifImg (ext) {
      let res = false
      let types = "bmp，jpg，png，tif，gif，pcx，tga，exif，fpx，svg，psd，cdr，pcd，dxf，ufo，eps，ai，raw，wmf, jpeg"
      if (types.indexOf(ext) != -1) {
        res = true
      }
      return res
    },
    getImgUrl (path) {
      return process.env.VUE_APP_BASE_API + '/file/download/resource?resource=' + path
    },
    getFiles () {
      if (!this.filesUpdated) {
        this.filesUpdated = true;
        this.queryParams.partId = this.partId;
        this.queryParams.fieldId = this.fieldId;
        listFile(this.queryParams).then(response => {
          this.newTableData = response.rows.length == 0 ? [] : response.rows;
          this.total = response.total;
          this.loading = false
        })
        this.$nextTick(() => {
          this.filesUpdated = false;
        });
      }
    },
    // 查看文件
    lookOver (file) {
      fileView(file.id).then(response => {
        window.open(response.data);
      })
    },
    openFile (file,key) {
      if(key){
        openFileView(file.id).then(response => {
          let urlData = response.data ;
          let url = 'sdm://openfile?type='+key+'&url='+ urlData;
          window.open(url);
        })
      }
    }
  }
}

</script>

<style lang="scss" scoped>
::v-deep .el-table--medium .el-table__cell {
  padding: 5px 0;
}

//给一个透明的边框，为了占位
::v-deep .el-col {
  border: 0.5px solid transparent;
}
::v-deep .el-dialog__body {
  max-height: 90vh;
  overflow: scroll;
}
::v-deep .el-checkbox__label {
  white-space: normal;
}
.el-checkbox {
  display: block;
}
.modal-img {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  cursor: move;
  &-wrap {
    border: 1px solid #33333345;
    position: relative;
    width: 95%;
    height: 35vh;
    overflow: hidden;
    margin-bottom: 1vh;
  }
}
.svg-icon {
  font-size: 20px;
}

</style>
